import { Body, Inject, Post, Get } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { OrderOrderEntity } from '../../entity/order';
import { OrderOrderService } from '../../service/order';
import { BaseSysUserEntity } from '../../../base/entity/sys/user';
import { UserInfoEntity } from '../../../user/entity/info';
import { OrderShopEntity } from '../../entity/shop';
import { AgentRelationEntity } from '../../../agent/entity/agentRelation';

/**
 * 订单信息
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: OrderOrderEntity,
  service: OrderOrderService,
  pageQueryOp: {
    keyWordLikeFields: ['a.orderNo'],
    fieldEq: [
      'a.id',
      'c.phone',
      'c.nickName',
      'a.payStatus',
      'a.orderProgress',
      'a.shopId',
      'd.cityId as shopCityId',
    ],
    select: [
      'a.*',
      // 'b.username',
      'b.nickName as adminName',
      'c.nickName as userNickName',
      'd.name as shopName',
      'c.phone as userPhone',
      'c.avatarUrl',
      'd.cityId as shopCityId',
      // 'a.lensQuantity as lensQuantity',
    ],
    join: [
      {
        entity: BaseSysUserEntity,
        alias: 'b',
        condition: 'a.adminId = b.id',
        type: 'leftJoin',
      },
      {
        entity: UserInfoEntity,
        alias: 'c',
        condition: 'a.userId = c.id', // Assuming userId in order_order refers to UserInfoEntity's id for app users
        type: 'leftJoin',
      },
      {
        entity: OrderShopEntity,
        alias: 'd',
        condition: 'a.shopId = d.id',
        type: 'leftJoin',
      },
    ],
    where: async ctx => {
      const { userPhone, userNickName, shopCityId, isAgent, startTime, endTime, dateTimeStartTime, dateTimeEndTime } = ctx.request.body;
      const where = [];
      console.log(userPhone, userNickName, shopCityId);
      if (userPhone) {
        where.push(['c.phone = :userPhone', { userPhone }]);
      }

      if (userNickName) {
        where.push(['c.nickName = :userNickName', { userNickName }]);
      }

      if (shopCityId) {
        where.push(['d.cityId = :shopCityId', { shopCityId }]);
      }

      if (startTime && endTime) {
        where.push(['a.createTime BETWEEN :startTime AND :endTime', { startTime, endTime }]);
      }

      if (dateTimeStartTime && dateTimeEndTime) {
        where.push([
          'a.createTime BETWEEN :startTime AND :endTime',
          { 
            startTime: dateTimeStartTime,
            endTime: dateTimeEndTime 
          }
        ]);
      }

      return where;
    },
    extend: find => {
      find.groupBy('a.id'); // 按订单ID分组，以便聚合商品名称
      return find;
    },
  },
})
export class AdminOrderOrderController extends BaseController {
  @Inject()
  orderOrderService: OrderOrderService;

  // 根据orderId进行分账，post方法
  @Post('/share')
  async shareOrder(@Body() body: { orderId: number }) {
    return this.orderOrderService.shareOrder(body.orderId);
  }

  // 后台根据用户名手机号商品ID创建订单
  @Post('/createOrderBackend')
  async createOrderBackend(
    @Body()
    body: {
      userName: string;
      userPhone: string;
      GoodIds: number[];
      payImg: string;
    }
  ) {
    const res = await this.orderOrderService.createOrderBackend(body);
    console.log(res);
    return this.ok(res);
  }

  // 后台根据用户名手机号商品ID创建订单
  @Post('/createCustomerOrderBackend')
  async createCustomerOrderBackend(
    @Body()
    body: {
      userName: string;
      userPhone: string;
      GoodIds: number[];
      payImg: string;
    }
  ) {
    const res = await this.orderOrderService.createCustomerOrderBackend(body);
    console.log(res);
    return this.ok(res);
  }

  // 按钮鉴权
  @Get('/createOrderBackendAuth')
  async createOrderBackendAuth() {
    const res = await this.orderOrderService.createOrderBackendAuth();
    return this.ok(res);
  }

  // 根据goodsId查询订单商品信息
  @Post('/getGoodsById')
  async getGoodsById(@Body() body: { goodsId: number }) {
    const res = await this.orderOrderService.getGoodsById(body.goodsId);
    console.log(res);
    return this.ok(res);
  }

  // 分账订单详情
  @Post('/getShareOrderDetail')
  async getShareOrderDetail(@Body() body: { orderId: number }) {
    const res = await this.orderOrderService.getShareOrderDetail(body);
    // console.log(res);
    return this.ok(res);
  }
}
